from flask import Flask, jsonify, render_template, request, redirect, url_for
from models import db, Style, Platform, Status, Info
import os

# 初始化Flask应用
app = Flask(__name__)

# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///data.db'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db.init_app(app)

# 确保数据库文件存在
if not os.path.exists('data.db'):
    # 创建数据库表（首次运行时创建）
    with app.app_context():
        db.create_all()

# 信息列表路由
#####################################################################
# 支持新增、删除
@app.route('/', methods=['GET', 'DELETE'])
def info_list():
    from utils import paginate
    from models import Info
    if request.method == 'GET':
        #query = Info.query.join(Info.platform).join(Info.style).join(Info.status)
        query = Info.query.join(Info.platform).join(Info.style)
        #query = Info.query.all()
        pager = paginate(query)
        return render_template('info_list.html', pager=pager)
    if request.method == 'DELETE':
        # 删除条目
        id = request.form.get('id')
        info = Info.query.get(id)
        if info:
            db.session.delete(info)
    try:
        db.session.commit()
        return jsonify({'status':'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error','message': str(e)}), 400
# 点击新增按钮时，跳转到新增信息页面
@app.route('/new_info')
def new_info_form():
    platforms = Platform.query.all()
    styles = Style.query.all()
    statuses = Status.query.all()
    return render_template('new_info.html', platforms=platforms, styles=styles, statuses=statuses)
# 保存新增信息
@app.route('/save_info', methods=['POST'])
def save_info():
    try:                
        new_info = Info(
            title=request.form.get('title'),
            platform_id=request.form.get('platform_id'),
            style_id=request.form.get('style_id'),
            status_id=request.form.get('status_id')
        )
        db.session.add(new_info)
        db.session.commit()
        return redirect('/')
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 400
################################################################################

################################################################################
# 字典管理路由
# 支持新建、更新、删除
@app.route('/dict/<dict_type>', methods=['GET', 'POST', 'PUT', 'DELETE'])
def dict_list(dict_type):
    from utils import paginate
    model_map = {
        'style': Style,
        'platform': Platform,
        'status': Status
    }
    model = model_map.get(dict_type)
    if not model:
        return jsonify({'error': 'Invalid dictionary type'}), 404

    if request.method == 'GET':
        items = model.query.all()
        return render_template('dict_list.html', dict_type=dict_type, items=items)
    elif request.method == 'POST':
        # 新建条目
        name = request.form.get('name')
        new_item = model(name=name)
        db.session.add(new_item)
    elif request.method == 'PUT':
        # 更新条目
        id = request.form.get('id')
        name = request.form.get('name')
        item = model.query.get(id)
        if item:
            item.name = name
    elif request.method == 'DELETE':
        # 删除条目
        id = request.form.get('id')
        item = model.query.get(id)
        if item:
            db.session.delete(item)

    try:
        db.session.commit()
        return jsonify({'status': 'success'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': str(e)}), 400
################################################################################


if __name__ == '__main__':
    app.run(debug=True)